import requests


# 发送想要翻译的文字
def post_text(url, data, headers):
    try:
        r = requests.post(url=url, headers=headers, data=data)
        r.raise_for_status()
        return r.json()
    except:
        # 如果没翻译成功就返回空字符串
        return ""


# 打印翻译后的英文
def print_result(result):
    translation = result[0].get('translations')[0].get('text')
    print(translation)


# 主程序
def main():
    url = 'https://cn.bing.com/ttranslatev3?isVertical=1&&IG=9CE9C73BA9EF4F09AC736861072FD539&IID=translator.5023.1'
    data = {'fromLang': 'zh-Hans', 'text': '请输入', 'to': 'en', 'token': 'InlKFa2PZTWzSRT7miAq9ayhLKAKVMbm', 'key': 1656298614652}
    data['text'] = input("输入您想翻译的中文！我会帮你翻译成英文！\n>>>:")
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53'}
    result = post_text(url, data, headers)
    if result:
        print_result(result)
    else:
        print("翻译失败！")


if __name__ == '__main__':
    main()
